// app/service/jwt.js
const AuthException = require('../exception/auth')
const UUID = require('uuid').v4
const Service = require('egg').Service
const dayjs = require('dayjs')

class JwtService extends Service {
	// 生成token
	async createToken(userId) {
		const now = dayjs().unix()
		const config = this.app.config.jwt
		const token = this.app.jwt.sign(
			{
				jti: UUID(),
				iat: now,
				nbf: now,
				exp: now + config.expiresIn,
				uid: userId,
			},
			config.secret
		)
		return token
	}
	// 验证token
	async verifyToken(token) {
		if (!token) {
			// 如果token不存在就抛出异常
			throw new AuthException()
		}
		token = token?.replace('Bearer ', '')
		const secret = this.app.config.jwt.secret
		try {
			this.app.jwt.verify(token, secret)
		} catch (e) {
			// 如果token验证失败直接抛出异常
			// 通过消息判断token是否过期
			if (e.message === 'jwt expired') {
				throw new AuthException('令牌过期', 401)
			}
			throw new AuthException()
		}
		return true
	}
	// 通过token获取用户id
	async getUserIdFromToken(token) {
		token = token?.replace('Bearer ', '')
		const isAccess = await this.verifyToken(token)
		// 解析token
		let res
		if (isAccess) {
			res = this.app.jwt.decode(token)
		}

		return res.uid
	}
}
module.exports = JwtService
